<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>了解闭包及作用域 | Jaho’s Blog</title>
    <meta name="generator" content="VuePress 1.8.0">
    <link rel="icon" href="/favicon.ico">
    <link rel="manifest" href="/manifest.json">
    <meta name="description" content="记录日常学习工作">
    
    <link rel="preload" href="/assets/css/0.styles.5b8fe0a4.css" as="style"><link rel="preload" href="/assets/js/app.6514719e.js" as="script"><link rel="preload" href="/assets/js/2.ea114ffb.js" as="script"><link rel="preload" href="/assets/js/34.20404dc4.js" as="script"><link rel="preload" href="/assets/js/4.e093c564.js" as="script"><link rel="prefetch" href="/assets/js/10.13203aa5.js"><link rel="prefetch" href="/assets/js/11.099868c4.js"><link rel="prefetch" href="/assets/js/12.c8365e17.js"><link rel="prefetch" href="/assets/js/13.89751e7c.js"><link rel="prefetch" href="/assets/js/14.31f563eb.js"><link rel="prefetch" href="/assets/js/15.08b381b6.js"><link rel="prefetch" href="/assets/js/16.1a3867de.js"><link rel="prefetch" href="/assets/js/17.7dd4e0c6.js"><link rel="prefetch" href="/assets/js/18.907c4597.js"><link rel="prefetch" href="/assets/js/19.fac8aa1a.js"><link rel="prefetch" href="/assets/js/20.73fe0e75.js"><link rel="prefetch" href="/assets/js/21.5c50aa1c.js"><link rel="prefetch" href="/assets/js/22.83d03663.js"><link rel="prefetch" href="/assets/js/23.061e7ac0.js"><link rel="prefetch" href="/assets/js/24.cc7e9011.js"><link rel="prefetch" href="/assets/js/25.fa6c7aef.js"><link rel="prefetch" href="/assets/js/26.39392f70.js"><link rel="prefetch" href="/assets/js/27.204436be.js"><link rel="prefetch" href="/assets/js/28.3f54c157.js"><link rel="prefetch" href="/assets/js/29.799d048c.js"><link rel="prefetch" href="/assets/js/3.6c5d6214.js"><link rel="prefetch" href="/assets/js/30.deed02f3.js"><link rel="prefetch" href="/assets/js/31.5916873b.js"><link rel="prefetch" href="/assets/js/32.b0634144.js"><link rel="prefetch" href="/assets/js/33.734675b8.js"><link rel="prefetch" href="/assets/js/35.d93b829f.js"><link rel="prefetch" href="/assets/js/36.b0692d8d.js"><link rel="prefetch" href="/assets/js/37.3dffa306.js"><link rel="prefetch" href="/assets/js/38.04649a97.js"><link rel="prefetch" href="/assets/js/39.7dfcdc32.js"><link rel="prefetch" href="/assets/js/40.04914511.js"><link rel="prefetch" href="/assets/js/41.ced85449.js"><link rel="prefetch" href="/assets/js/42.72739213.js"><link rel="prefetch" href="/assets/js/43.de1cff16.js"><link rel="prefetch" href="/assets/js/44.48e301ae.js"><link rel="prefetch" href="/assets/js/45.870a7650.js"><link rel="prefetch" href="/assets/js/46.657f15b8.js"><link rel="prefetch" href="/assets/js/47.3df1bfdb.js"><link rel="prefetch" href="/assets/js/48.f4e4e774.js"><link rel="prefetch" href="/assets/js/49.632bf611.js"><link rel="prefetch" href="/assets/js/5.6531e181.js"><link rel="prefetch" href="/assets/js/50.a8018493.js"><link rel="prefetch" href="/assets/js/51.cb424f59.js"><link rel="prefetch" href="/assets/js/52.a9f595dc.js"><link rel="prefetch" href="/assets/js/53.cf8a9ec0.js"><link rel="prefetch" href="/assets/js/54.46d774a3.js"><link rel="prefetch" href="/assets/js/55.3574f9b8.js"><link rel="prefetch" href="/assets/js/56.baf60ba5.js"><link rel="prefetch" href="/assets/js/57.af42b559.js"><link rel="prefetch" href="/assets/js/58.9300cb59.js"><link rel="prefetch" href="/assets/js/6.00f437ec.js"><link rel="prefetch" href="/assets/js/7.58ac7166.js"><link rel="prefetch" href="/assets/js/8.1b9c5002.js"><link rel="prefetch" href="/assets/js/9.5c076362.js">
    <link rel="stylesheet" href="/assets/css/0.styles.5b8fe0a4.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="Jaho’s Blog" class="logo"> <span class="site-name can-hide">Jaho’s Blog</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/posts/" class="nav-link router-link-active">
  技术博客
</a></div> <a href="https://juejin.cn/user/26836627369806" target="_blank" rel="noopener noreferrer" class="repo-link">
    个人主页
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/posts/" class="nav-link router-link-active">
  技术博客
</a></div> <a href="https://juejin.cn/user/26836627369806" target="_blank" rel="noopener noreferrer" class="repo-link">
    个人主页
    <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav>  <ul class="sidebar-links"><li><a href="/posts/" aria-current="page" class="sidebar-link">写在前面</a></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>工作问题解决</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading open"><span>JavaScript</span> <span class="arrow down"></span></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/posts/JavaScript/闭包作用域.html" class="active sidebar-link">了解闭包及作用域</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/posts/JavaScript/闭包作用域.html#性能优化" class="sidebar-link">性能优化</a></li></ul></li><li><a href="/posts/JavaScript/短路原则.html" class="sidebar-link">布尔判定和短路原则</a></li><li><a href="/posts/JavaScript/类型转换.html" class="sidebar-link">类型转换</a></li><li><a href="/posts/JavaScript/数组转树.html" class="sidebar-link">数组转树方案</a></li><li><a href="/posts/JavaScript/数组拍平.html" class="sidebar-link">数组拍平方案</a></li><li><a href="/posts/JavaScript/数组求和.html" class="sidebar-link">数组求和（不允许使用循环）</a></li><li><a href="/posts/JavaScript/async.html" class="sidebar-link">async await实战</a></li><li><a href="/posts/JavaScript/defer.html" class="sidebar-link">JS文档的解析:async、defer 属性</a></li><li><a href="/posts/JavaScript/set.html" class="sidebar-link">Set笔记</a></li><li><a href="/posts/JavaScript/map.html" class="sidebar-link">Map笔记</a></li><li><a href="/posts/JavaScript/call.html" class="sidebar-link">手写call、bind、apply</a></li><li><a href="/posts/JavaScript/eventBus.html" class="sidebar-link">Eventbus使用</a></li><li><a href="/posts/JavaScript/instanceof.html" class="sidebar-link">浅析instanceof的实现</a></li><li><a href="/posts/JavaScript/function.html" class="sidebar-link">如何优雅的用function实现一个class</a></li><li><a href="/posts/JavaScript/require.html" class="sidebar-link">浅析commonjs中require的执行方式</a></li><li><a href="/posts/JavaScript/promise.html" class="sidebar-link">手写Promise</a></li></ul></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Css</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Nodejs</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Vue</span> <span class="arrow right"></span></p> <!----></section></li><li><section class="sidebar-group collapsable depth-0"><p class="sidebar-heading"><span>Git</span> <span class="arrow right"></span></p> <!----></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="了解闭包及作用域"><a href="#了解闭包及作用域" class="header-anchor">#</a> 了解闭包及作用域</h1> <h3 id="☀️-什么是闭包"><a href="#☀️-什么是闭包" class="header-anchor">#</a> ☀️ 什么是闭包</h3> <blockquote><p>一个函数和对其周围状态（<strong>lexical environment，词法环境</strong>）的引用捆绑在一起（或者说函数被引用包围），这样的组合就是<strong>闭包</strong>（<strong>closure</strong>）。也就是说，闭包让你可以在一个内层函数中访问到其外层函数的作用域。在 JavaScript 中，每当创建一个函数，闭包就会在函数创建的同时被创建出来----MDN</p></blockquote> <p>简单来说：闭包存在俩个特点</p> <ol><li>在一个函数中返回另外一个函数</li> <li>内函数使用了外函数的参数或者是变量
最常见的写法是长这样子的</li></ol> <blockquote><p>outSide函数中有一个局部变量name和一个inSide函数，inSide属于outSide的内部函数，但是inSide中没有自己的变量，但他可以访问到外部函数outSide的变量。当outSide函数执行完之后，一般来说一个函数中的局部变量执行完就无法访问了。然而在inSide仍然能拿到变量的值，所以闭包情况与此不同，执行上下文被销毁，但创建时所在词法环境依然存在，变量仍然能够保存下来。</p></blockquote> <h3 id="☀️-闭包的使用场景"><a href="#☀️-闭包的使用场景" class="header-anchor">#</a> ☀️ 闭包的使用场景</h3> <p>一个简单的应用场景，该方法使用了一个闭包返回设置fontsize 的不同大小，我们可以通过设置不同的参数在同一个闭包上，返回同一函数不同参数的几种方法，这样就可以批量的产出我们需要用到的函数</p> <h4 id="_1-柯里化函数"><a href="#_1-柯里化函数" class="header-anchor">#</a> 1.柯里化函数</h4> <blockquote><p>柯里化主要是对相同参数的函数进行复用，比如下图可以实现一个计算面积大小的函数。</p></blockquote> <h4 id="_2-模拟私有方法"><a href="#_2-模拟私有方法" class="header-anchor">#</a> 2.模拟私有方法</h4> <blockquote><p>在<code>JavaScript</code>中，没有支持声明私有变量，闭包可以用来模拟私有方法</p></blockquote> <p>在下面这段代码中，我们需要生成多个计数器，多个计数器之间互不干扰，各自执行自己的计数加减，通过闭包的方式可以将计算的加减方法变成每个计数器的公有函数法，并在其中访问计数器的私有方法和变量，这样各个计数器之间不会影响到。</p> <p>在方法执行的过程中，改变这个私有变量的值，闭包的词法环境被改变，但不会影响另一个闭包中的变量，因为两个闭包之间都是私有的。</p> <h2 id="性能优化"><a href="#性能优化" class="header-anchor">#</a> 性能优化</h2> <div class="language- extra-class"><pre class="language-text"><code>function MyObject(name, message) {
  this.name = name.toString();
  this.message = message.toString();
  this.getName = function() {
    return this.name;
  };

  this.getMessage = function() {
    return this.message;
  };
}
</code></pre></div><p>上面的闭包写法在日常中可能并不太经常存在，由于闭包对性能方面会有一定的影响，所以一般是比较少用到闭包的，对于上面的写法可以通过关联对象原型的方法进行使用，比如下面这段例子，变量已经通过this的方式放在对象中，所以我们需要用到的方法可以直接在原型上进行绑定。</p> <h4 id="作用域的认识"><a href="#作用域的认识" class="header-anchor">#</a> 作用域的认识</h4> <p>开始的时候我们说到闭包是在一个函数中返回另一个函数，内部函数可以访问到外部函数的作用域，那么这个作用域是是指什么呢，作用域其实就是一段段的代码块，比如声明变量和方法或者执行方法的代码，处在不同位置会成为不同的作用域，一般分为三块作用域</p> <ul><li>全局作用域</li> <li>函数作用域</li> <li>块级作用域</li></ul> <h4 id="全局作用域"><a href="#全局作用域" class="header-anchor">#</a> 全局作用域</h4> <blockquote><p>像以下这种变量、函数、函数执行都在全局作用下，不在函数中，或者一个大括号中声明的，则视为处在全局作用域中</p></blockquote> <h4 id="函数作用域"><a href="#函数作用域" class="header-anchor">#</a> 函数作用域</h4> <blockquote><p>这个比较简单，在函数中的代码都处在函数作用域中，外部访问不到，进行访问的时候会报错，通常也叫做局部作用域</p></blockquote> <h4 id="块级作用域"><a href="#块级作用域" class="header-anchor">#</a> 块级作用域</h4> <blockquote><p>块级作用域主要保存着let和const声明的变量，主要表现为一个大括号，大括号中let和const声明的变量视为存在于块级作用域中，在大括号外无法访问，但是var声明的为全局变量，会造成变量提升，在大括号外仍然是可以访问的到的。</p></blockquote></div> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">上次更新:</span> <span class="time">2023-01-04 10:56:12</span></div></footer> <div class="page-nav"><p class="inner"><span class="prev">
      ←
      <a href="/posts/项目问题解决/小程序踩坑.html" class="prev">
        小程序踩坑
      </a></span> <span class="next"><a href="/posts/JavaScript/短路原则.html">
        布尔判定和短路原则
      </a>
      →
    </span></p></div> </main></div><div class="global-ui"><!----><!----></div></div>
    <script src="/assets/js/app.6514719e.js" defer></script><script src="/assets/js/2.ea114ffb.js" defer></script><script src="/assets/js/34.20404dc4.js" defer></script><script src="/assets/js/4.e093c564.js" defer></script>
  </body>
</html>
